﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using SealManagement.Common;
using SealManagement.Models;
using SealManagement.SqlData;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace SealManagement.Components
{
    [ViewComponent(Name = "Navigation")]
    public class NavigationViewComponent : ViewComponent
    {
        private SignContext _context;
        private IMemoryCache _cache;
        public NavigationViewComponent(SignContext context, IMemoryCache cache)
        {
            _context = context;
            _cache = cache;
        }
        public IViewComponentResult Invoke()
        {
            #region 登录
            if (HttpContext.User.Claims.Count() == 0)
            {
                return View();
            }
            #endregion
            var resListMenus = new List<MenuItem>();
            if (_cache.Get("MenuItems") == null)
            {
                var utypeStr = HttpContext.User.FindFirst(ClaimTypes.Role).Value;
                var utype = 0;
                if (utypeStr == userType.SignMaker.ToString())
                    utype = 1;
                var listMenu = _context.MenuItems.Where(p => p.UserType == utype && p.ParentId == 0).ToList();
                foreach (var item in listMenu)
                {
                    var ChildNodes = _context.MenuItems.Where(p => p.ParentId == item.Id).ToList();
                    item.ChildNodes = ChildNodes;
                }
                _cache.Set("MenuItems", listMenu);
                resListMenus = listMenu;
            }
            else
            {
                resListMenus = _cache.Get("MenuItems") as List<MenuItem>;
            }
            return View(resListMenus);
        }
    }
}
